<?php
namespace App\Services\System;

use Illuminate\Support\Facades\DB;
use App\Models\System\DefaultGroup;
use Illuminate\Database\Eloquent\Builder;

class DefinedGroupService
{

    /**
     * 列表
     * @author lxy
     * @datetime 2022-11-22
     */
    public function getDgList($request)
    {
        $limit = $request['limit'] ?? 10;
        $where = [];
        $where[] = ['status','=',1];
        $where[] = ['pid','=',0];
        $where[] = ['is_node','=',1];
        
        if(!empty($request['search']['created_at'])){     
            $created_at = explode(' - ',$request['search']['created_at']);
            $where[] = ['created_at','>=',$created_at[0]];
            $where[] = ['created_at','<=',$created_at[1]];
        }
   
        $result = DefaultGroup::select('*')
                ->where($where)
                ->with(['user','childrenMembres'])
                ->when(!empty($request['search']['author']),function($q) use($request){
                    $q->whereHas('user',function(Builder $query) use($request){
                        $query->where('user_name','like',"%".$request['search']['author']."%");
                    });
                })
                ->orderBy('created_at','desc')
                ->paginate($limit)->toArray();

        foreach($result['data'] as $k=>&$v){
            $i = 0;
            foreach($v['children_membres'] as $k2=>$v2){
                if($v2['is_node'] == 1){
                    foreach($v2['children_membres'] as $k3=>$v3){
                        if(!empty($v3)){
                            $i++;
                        }
                    }
                }else{
                    $i++;
                }
            }
            $v['counts'] = $i;
        }

        $result['limit'] = $limit;
  
        return $result;
    }


    /**
     * 二级分组列表
     * @author lxy
     * @datetime 2022-11-22
     */
    public function getDgTwoList($request)
    {
        $limit = $request['limit'] ?? 10;
        $where = [];
        $where[] = ['status','=',1];
        $where[] = ['pid','=',(int)$request['id']];  
         
        $result = DefaultGroup::select('*')
                ->where($where)
                ->with(['user','childrenMembres'])
                ->orderBy('created_at')
                ->paginate($limit)
                ->toArray();

                foreach($result['data'] as $k=>&$v){     
                    $v['counts'] = count($v['children_membres']);
                }
     
        $result['limit'] = $limit;
  
        return $result;
    }

    /**
     * 三级分组列表
     * @author lxy
     * @datetime 2022-11-22
     */
    public function getDgThreeList($request)
    {
        $limit = $request['limit'] ?? 10;
        $where = [];
        $where[] = ['status','=',1];
        $where[] = ['is_node','=',2];
        $where[] = ['pid','=',(int)$request['id']];
        !empty($request['search']['title'])     && $where[] = ['title','like','%'.$request['search']['title'].'%'];
         
        $result = DefaultGroup::select('*')
                ->where($where)
                ->with(['user'])
                ->orderBy('created_at')
                ->paginate($limit)
                ->toArray();
     
        $result['limit'] = $limit;
  
        return $result;
    }

    /**
     * 添加分组
     * @author lxy
     * @datetime 2022-11-22
     */
    public function addDf($request)
    {
        $id = !empty($request['id'])?$request['id']:0;
        unset($request['id']);
        if($id){      
            $result = DefaultGroup::whereId($id)->update($request);
            return $result;
        }else{
            $request['author'] = auth()->user()->user_id;
            $result = DefaultGroup::create($request);
            return $result->id;
        }
        
    }

    /**
     * 删除
     * @author lxy
     * @datetime 2022-11-22
     */
    public function delDf($request)
    {
        $id = (int)$request['id'];
        $result = DefaultGroup::whereId($id)->update(['status'=>0]);
        return $result;
    }

    /**
     * 批量删除
     * @author lxy
     * @datetime 2022-11-22
     */
    public function delAllDf($request)
    {
        if(empty($request['params'])){
            throw new \Exception('请选择数据');
        }
        $ids = array_column($request['params'],'id');
        $result = DefaultGroup::whereIn('id',$ids)->update(['status'=>0]);
        return $result;
    }

    /**
     * 添加人员
     * @author lxy
     * @datetime 2022-11-23
     */
    public function addDfMembers($request)
    {
        $pid = (int)$request['pid'];
        $user_id = auth()->user()->user_id;
        DefaultGroup::where([
            ['pid','=',$pid],
            ['is_node','=',2]
        ])->delete();
        foreach($request['member'] as $k=>&$v){
            $v['pid'] = $pid;
            $v['is_node'] = 2;
            $v['author'] = $user_id;
            $v['created_at'] = date('Y-m-d H:i:s');
            $v['updated_at'] = date('Y-m-d H:i:s');
        }
       
      
        $menbers = array_column($request['member'],'value');
      
        if(DefaultGroup::whereIn('value',$menbers)->get()->toArray()){
            throw new \Exception('已选人员有重复，请确认后重新添加');
        }
       
        $result = DefaultGroup::insert($request['member']);
        if(!$result){
            throw new \Exception('添加失败');
        }
        return [];
    }

    /**
     * 获取人员
     * @author lxy
     * @datetime 2022-11-23
     */
    public function getDfMembers($request)
    {
        $pid = (int)$request['pid'];
        $result = DefaultGroup::wherePid($pid)->whereStatus(1)->where('is_node','=',2)->select('value','title')->get()->toArray();
        if(!$result){
            return [
                'data'=>[],
                'data_true'=>[],
            ]; 
        }
        return [
            'data'=>$result,
            'data_true'=>array_column($result,'value'),
        ];
    }

    /**
     * 获取自定义分组成员
     * @author lxy
     * @datetime 2022-11-24
     */
    public function getDfGroupMembers($request)
    {
        $result = DefaultGroup::where([
            ['status','=',1],
            ['type','=',1],
            ['pid','=',0],
        ])
        ->select('id','title','pid','value')
        ->with(['children'=>function($q){
            $q->where('status',1);
        }])
        ->get()->toArray();

        $i = 0;
    
        if(isset($request['id']) && !empty($request['id'])){
            $ids = explode(',',$request['id']);
            foreach($result as $k=>&$v){
                if(!empty($v['children'])){
                    foreach($v['children'] as $k2=>&$v2){                
                        if(empty($v2['children'])){
                            if(in_array($v2['id'],$ids)){
                                 $v2['checked'] = true;
                                 $i++;
                            }
                        }else{
                            foreach($v2['children'] as $k3=>&$v3){
                                if(empty($v3['children'])){
                                    if(in_array($v3['id'],$ids)){
                                        $v3['checked'] = true;
                                        $i++;
                                    }
                                }                                                  
                            }
                        }
                    }
                }
            }
        }

        if($result){
            $result[0]['spread'] = true;
            $result[0]['checked_sum'] = $i;
        }

        return $result;
    }

    /**
     * 获取成员
     * @author lxy
     * @datetime 2022-11-24
     */
    public function getDfMembersToId($request)
    {
        $group = !empty($request['group'])?$request['group']:[];
        if(!$group){
            return [];
        } 
        $groupIds = self::loop_group($group);
        $users = DefaultGroup::select('value','title')->whereIn('id',$groupIds)
                ->where('status',1)
                ->where('is_node',2)
                ->get()->toArray();
        return $users;
    }

    /**
     * 递归循环多维数组 [多维数组，提取所有的id]
     * @author lxy
     * @datetime 2022-11-24
     * @return array 
     */
    private static function loop_group($data)
    {
        static $arr = [];
        foreach($data as $k=>$v){
            array_push($arr,$v['id']);
            if(!empty($v['children'])){
                self::loop_group($v['children']);
            }
        }
        return $arr;
    }


}

?>